<template>
  <div class="order-detail-container h-full w-full p-5">
    <div class="card-box h-full">
      <el-card class="order-detail-card">
        <template #header>
          <div class="flex items-center justify-between">
            <h2 class="text-xl font-bold">订单详情</h2>
            <el-button @click="goBack">返回</el-button>
          </div>
        </template>

        <el-skeleton :loading="loading" animated>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="订单号">{{
              orderDetail.orderNo
            }}</el-descriptions-item>
            <el-descriptions-item label="产品名称">{{
              orderDetail.productName
            }}</el-descriptions-item>
            <el-descriptions-item label="订单价格"
              >{{ orderDetail.orderPayPrice }}元</el-descriptions-item
            >
            <el-descriptions-item label="订单状态">
              <el-tag
                :type="getOrderStatusInfo(orderDetail.orderState)?.type"
                >{{
                  getOrderStatusInfo(orderDetail.orderState)?.msg || '未知'
                }}</el-tag
              >
            </el-descriptions-item>
            <el-descriptions-item label="预约日期">{{
              appointmentDate
            }}</el-descriptions-item>
            <el-descriptions-item label="预约时间">
              <div class="appointment-times">
                <div
                  v-for="(timeSlot, index) in formattedTimeSlots"
                  :key="index"
                  class="time-slot"
                >
                  {{ timeSlot.time
                  }}<el-tag :type="getOrderStatusInfo(timeSlot.state)?.type">{{
                    getOrderStatusInfo(timeSlot.state)?.msg || '未知'
                  }}</el-tag>
                </div>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{
              orderDetail.createTime
            }}</el-descriptions-item>
          </el-descriptions>
        </el-skeleton>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import {
  ElButton,
  ElCard,
  ElDescriptions,
  ElDescriptionsItem,
  ElSkeleton,
  ElTag,
} from 'element-plus';
import { getOrderDetails } from '#/api/order';

// 定义订单状态枚举（保持不变）
const ORDER_STATUS = {
  UNPAID: { state: 1, msg: '待支付', type: 'warning' },
  CANCELED: { state: 5, msg: '已取消', type: 'info' },
  TO_REDEMPTION: { state: 10, msg: '待核销', type: 'primary' },
  REFUND: { state: 15, msg: '已退款', type: 'danger' },
  REDEMPTION: { state: 20, msg: '已核销', type: 'success' },
  EXPIRED: { state: 25, msg: '已过期', type: 'info' },
} as const;

interface PriceDateTimeRange {
  endTime: string;
  id: string;
  price: number;
  startTime: string;
  state: number;
}

interface OrderDetail {
  id: string;
  orderNo: string;
  productName: string;
  orderPayPrice: number;
  state: number;
  createTime: string;
  updateTime: string;
  priceDateTimeRangeVOList?: PriceDateTimeRange[];
}

const route = useRoute();
const router = useRouter();

const loading = ref(false);
const orderDetail = ref<OrderDetail>({
  id: '',
  orderNo: '',
  productName: '',
  orderPayPrice: 0,
  state: 0,
  createTime: '',
  updateTime: '',
  priceDateTimeRangeVOList: [],
});

// 计算预约日期（取第一个时间段的开始日期）
const appointmentDate = computed(() => {
  if (
    orderDetail.value?.priceDateTimeRangeVOList?.length &&
    orderDetail.value.priceDateTimeRangeVOList[0]?.startTime
  ) {
    return orderDetail.value.priceDateTimeRangeVOList[0].startTime.split(
      ' ',
    )[0];
  }
  return '';
});

// 格式化时间段和状态
const formattedTimeSlots = computed(() => {
  if (orderDetail.value?.priceDateTimeRangeVOList?.length) {
    return orderDetail.value.priceDateTimeRangeVOList.map((item) => {
      const startTime = item.startTime.split(' ')[1].substring(0, 5);
      const endTime = item.endTime.split(' ')[1].substring(0, 5);
      return {
        time: `${startTime}-${endTime}`,
        ...item,
      };
    });
  }
  return [];
});

// 获取订单状态信息（使用原始ORDER_STATUS枚举）
const getOrderStatusInfo = (state: number) => {
  for (const status of Object.values(ORDER_STATUS)) {
    if (status.state === state) {
      return status;
    }
  }
  return null;
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 加载订单详情
const loadOrderDetail = async (orderId: string) => {
  loading.value = true;
  try {
    const { data } = await getOrderDetails(orderId);
    orderDetail.value = data;
  } catch (error) {
    console.error('加载订单详情失败:', error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  const orderId = route.params.id as string;
  if (orderId) {
    loadOrderDetail(orderId);
  }
});
</script>

<style scoped lang="scss">
.order-detail-container {
  .order-detail-card {
    :deep(.el-card__header) {
      border-bottom: 1px solid var(--el-border-color);
    }

    :deep(.el-descriptions__label) {
      width: 120px;
      font-weight: bold;
    }

    .appointment-times {
      display: flex;
      flex-direction: column;
      gap: 4px;

      .time-slot {
        padding: 4px 0;
        display: flex;
        align-items: center;
        span {
          margin-left: 8px;
        }
      }
    }
  }
}
</style>
